package spring.lottery.controller;

import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import spring.lottery.common.exception.ServerException;
import spring.lottery.common.exceptionCode.ResponseCodes;
import spring.lottery.common.pojo.ResponseMode;
import spring.lottery.common.pojo.VerificationCodeHtml;
import spring.lottery.common.util.CaptchaUtil;
import spring.lottery.common.util.MailUtil;
import spring.lottery.common.util.RedisUtil;
import spring.lottery.controller.param.LoginRequestParamByEmail;
import spring.lottery.controller.param.LoginRequestParamByUP;
import spring.lottery.controller.param.UserRequestParam;
import spring.lottery.dao.dataObject.UserDO;
import spring.lottery.dao.mapper.UserMapper;
import spring.lottery.server.UserServer;
import spring.lottery.server.exceptionCode.ServerConstantCode;

import java.util.Map;
import java.util.UUID;

import static spring.lottery.common.constant.Constants.EMAIL_TITLE;
import static spring.lottery.common.constant.Constants.LOGIN_EMAIL_PREFIX;


@Slf4j
@RestController
@RequestMapping("user")
public class UserController {


    @Autowired
    UserServer userServer;
    @Autowired
    MailUtil mailUtil;
    @Autowired
    RedisUtil redis;
    @Autowired
    UserMapper userMapper;

    /**
     * 注册用户
     */
    @RequestMapping("/register")
    public ResponseMode register(@Validated @RequestBody UserRequestParam user) {
        log.info("register user: {}", user);
        Boolean register = userServer.register(user);
        return register ? new ResponseMode(ResponseCodes.SUCCESS) : new ResponseMode(ResponseCodes.FAIL);
    }

    /**
     * 登录
     * 返回jwt令牌
     */
    @RequestMapping("/login")
    public ResponseMode login(@Validated @RequestBody LoginRequestParamByUP user) {
        log.info("login user: {}", user);
        String token = userServer.login(user);
        if(token == null) {
            return new ResponseMode(ResponseCodes.FAIL);
        }
        return new ResponseMode(ResponseCodes.SUCCESS, token);
    }

    /**
     * 使用email来登录 验证Email的正确性
     */
    @RequestMapping("/email")
    public ResponseMode captcha(@Validated @RequestBody LoginRequestParamByEmail user) {
        log.info("captcha user: {}", user);

        String token = userServer.login(user);

        return new ResponseMode(ResponseCodes.SUCCESS, Map.of("token", token));
    }

    /**
     * 获取到验证码
     */
    @RequestMapping("/verification-code/send")
    public ResponseMode getVerify(@NotBlank String email) {

        log.info("send verification code to user: {}", email);

        return ResponseMode.success(sendVerify(email));
    }

    private Boolean sendVerify(String email) {
        if (!verifyEmail(email)) {
            log.info("邮箱输入错误,没有该邮箱");
            throw new ServerException(ServerConstantCode.EMAIL_ERROR);
        }

        String verifyCode = UUID.randomUUID().toString().substring(0, 6);

        log.info("verifyCode = {}", verifyCode);

        redis.set(LOGIN_EMAIL_PREFIX + email, verifyCode, 60L);

        String html = new VerificationCodeHtml().toString().replace("%%s1", verifyCode)
                .replace("%%s2", email);

        return mailUtil.sendHtmlMail(email, EMAIL_TITLE, html);
    }

    private boolean verifyEmail(String email) {
        UserDO u = userMapper.getUserByEmail(email);

        if (u == null) {
            log.error("输入的邮箱不存在");
            return false;
        }

        return true;
    }
}
